package com.wangwenjun.concurrency.chapter14.atomicintegerarray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class UseAtomicIntegerArray {


    public static void main(String[] args) {
        show(()->{
            return new AtomicIntegerArray(10);
        }, a -> a.length(), (a, index)->{
            a.getAndIncrement(index);
        }, t-> System.out.println(t));


    }


    public static <T> void show(Supplier<T> supplier, Function<T, Integer> lengthFunction, BiConsumer<T, Integer> action, Consumer<T> endConsumer){
        ArrayList<Thread> threads = new ArrayList<>();
        T t = supplier.get();
        Integer arrayLength = lengthFunction.apply(t);

        for (int i = 0; i < arrayLength; i++) {
            threads.add(new Thread(()->{
                for (int j = 0; j < 10000; j++) {
                    action.accept(t, j % arrayLength);
                }
            }));
        }
        threads.forEach(e->e.start());

        threads.forEach(e->{
            try {
                e.join();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        });

        endConsumer.accept(t);

    }


}
